import json
import os
from datetime import datetime

class Book:
    """图书类，表示图书馆中的一本书"""
    def __init__(self, book_id, title, author, publisher, publication_year):
        self.book_id = book_id
        self.title = title
        self.author = author
        self.publisher = publisher
        self.publication_year = publication_year
        self.is_borrowed = False
        self.borrower = None
        self.borrow_date = None
        self.return_date = None
    
    def to_dict(self):
        """将Book对象转换为字典，用于存储"""
        return {
            'book_id': self.book_id,
            'title': self.title,
            'author': self.author,
            'publisher': self.publisher,
            'publication_year': self.publication_year,
            'is_borrowed': self.is_borrowed,
            'borrower': self.borrower,
            'borrow_date': self.borrow_date,
            'return_date': self.return_date
        }
    
    @classmethod
    def from_dict(cls, data):
        """从字典创建Book对象"""
        book = cls(
            data['book_id'],
            data['title'],
            data['author'],
            data['publisher'],
            data['publication_year']
        )
        book.is_borrowed = data['is_borrowed']
        book.borrower = data['borrower']
        book.borrow_date = data['borrow_date']
        book.return_date = data['return_date']
        return book

class Library:
    """图书馆类，管理所有图书和操作"""
    def __init__(self, data_file='library_data.json'):
        self.books = []
        self.data_file = data_file
        self.load_data()
    
    def load_data(self):
        """从文件加载图书数据"""
        if os.path.exists(self.data_file):
            try:
                with open(self.data_file, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                    self.books = [Book.from_dict(book_data) for book_data in data]
                print(f"成功加载 {len(self.books)} 本图书数据")
            except Exception as e:
                print(f"加载数据失败: {e}")
        else:
            print("未找到数据文件，将创建新的图书馆")
    
    def save_data(self):
        """将图书数据保存到文件"""
        try:
            with open(self.data_file, 'w', encoding='utf-8') as f:
                data = [book.to_dict() for book in self.books]
                json.dump(data, f, ensure_ascii=False, indent=4)
            print("数据已保存")
        except Exception as e:
            print(f"保存数据失败: {e}")
    
    def add_book(self, book):
        """添加图书到图书馆"""
        # 检查图书ID是否已存在
        if any(b.book_id == book.book_id for b in self.books):
            print(f"错误: 图书ID {book.book_id} 已存在")
            return False
        
        self.books.append(book)
        self.save_data()
        print(f"成功添加图书: {book.title}")
        return True
    
    def find_book_by_id(self, book_id):
        """通过ID查找图书"""
        for book in self.books:
            if book.book_id == book_id:
                return book
        return None
    
    def find_books_by_title(self, title):
        """通过标题查找图书（模糊匹配）"""
        return [book for book in self.books if title.lower() in book.title.lower()]
    
    def find_books_by_author(self, author):
        """通过作者查找图书（模糊匹配）"""
        return [book for book in self.books if author.lower() in book.author.lower()]
    
    def borrow_book(self, book_id, borrower):
        """借阅图书"""
        book = self.find_book_by_id(book_id)
        if not book:
            print(f"错误: 未找到ID为 {book_id} 的图书")
            return False
        
        if book.is_borrowed:
            print(f"错误: 图书《{book.title}》已被借阅")
            return False
        
        book.is_borrowed = True
        book.borrower = borrower
        book.borrow_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        book.return_date = None
        self.save_data()
        print(f"成功借阅图书《{book.title}》")
        return True
    
    def return_book(self, book_id):
        """归还图书"""
        book = self.find_book_by_id(book_id)
        if not book:
            print(f"错误: 未找到ID为 {book_id} 的图书")
            return False
        
        if not book.is_borrowed:
            print(f"错误: 图书《{book.title}》未被借阅")
            return False
        
        book.is_borrowed = False
        book.return_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        self.save_data()
        print(f"成功归还图书《{book.title}》")
        return True
    
    def display_all_books(self):
        """显示所有图书"""
        if not self.books:
            print("图书馆中没有图书")
            return
        
        print("\n===== 图书馆图书列表 =====")
        for book in self.books:
            status = "已借出" if book.is_borrowed else "可借阅"
            print(f"ID: {book.book_id}")
            print(f"标题: {book.title}")
            print(f"作者: {book.author}")
            print(f"出版社: {book.publisher}")
            print(f"出版年份: {book.publication_year}")
            print(f"状态: {status}")
            if book.is_borrowed:
                print(f"借阅人: {book.borrower}")
                print(f"借阅日期: {book.borrow_date}")
            print("------------------------")

def display_menu():
    """显示系统菜单"""
    print("\n===== 图书管理系统 =====")
    print("1. 添加图书")
    print("2. 查找图书（按ID）")
    print("3. 查找图书（按标题）")
    print("4. 查找图书（按作者）")
    print("5. 借阅图书")
    print("6. 归还图书")
    print("7. 显示所有图书")
    print("8. 保存数据")
    print("0. 退出系统")
    return input("请选择操作: ")

def main():
    """主函数，处理用户交互"""
    library = Library()
    
    while True:
        choice = display_menu()
        
        if choice == '1':
            # 添加图书
            try:
                book_id = input("请输入图书ID: ")
                title = input("请输入图书标题: ")
                author = input("请输入图书作者: ")
                publisher = input("请输入出版社: ")
                publication_year = input("请输入出版年份: ")
                
                book = Book(book_id, title, author, publisher, publication_year)
                library.add_book(book)
            except Exception as e:
                print(f"添加图书失败: {e}")
        
        elif choice == '2':
            # 按ID查找图书
            book_id = input("请输入要查找的图书ID: ")
            book = library.find_book_by_id(book_id)
            if book:
                status = "已借出" if book.is_borrowed else "可借阅"
                print("\n===== 图书信息 =====")
                print(f"ID: {book.book_id}")
                print(f"标题: {book.title}")
                print(f"作者: {book.author}")
                print(f"出版社: {book.publisher}")
                print(f"出版年份: {book.publication_year}")
                print(f"状态: {status}")
                if book.is_borrowed:
                    print(f"借阅人: {book.borrower}")
                    print(f"借阅日期: {book.borrow_date}")
            else:
                print(f"未找到ID为 {book_id} 的图书")
        
        elif choice == '3':
            # 按标题查找图书
            title = input("请输入要查找的图书标题: ")
            books = library.find_books_by_title(title)
            if books:
                print(f"\n找到 {len(books)} 本相关图书:")
                for book in books:
                    status = "已借出" if book.is_borrowed else "可借阅"
                    print(f"ID: {book.book_id}, 标题: {book.title}, 作者: {book.author}, 状态: {status}")
            else:
                print(f"未找到标题包含 '{title}' 的图书")
        
        elif choice == '4':
            # 按作者查找图书
            author = input("请输入要查找的作者: ")
            books = library.find_books_by_author(author)
            if books:
                print(f"\n找到 {len(books)} 本相关图书:")
                for book in books:
                    status = "已借出" if book.is_borrowed else "可借阅"
                    print(f"ID: {book.book_id}, 标题: {book.title}, 作者: {book.author}, 状态: {status}")
            else:
                print(f"未找到作者包含 '{author}' 的图书")
        
        elif choice == '5':
            # 借阅图书
            book_id = input("请输入要借阅的图书ID: ")
            borrower = input("请输入借阅人姓名: ")
            library.borrow_book(book_id, borrower)
        
        elif choice == '6':
            # 归还图书
            book_id = input("请输入要归还的图书ID: ")
            library.return_book(book_id)
        
        elif choice == '7':
            # 显示所有图书
            library.display_all_books()
        
        elif choice == '8':
            # 保存数据
            library.save_data()
        
        elif choice == '0':
            # 退出系统
            print("感谢使用图书管理系统，再见！")
            break
        
        else:
            print("无效的选择，请重新输入")

if __name__ == "__main__":
    main()
